<?php

class user
{
	
	var $is_logged_in = false;
	
	var $user_info = array(
		'id' => -1,
		'user' => 'Guest',
		'rank' => 'guest'
	);
	
	function __construct($sid, $ip)
	{
		$user = session::exist($sid, $ip);
		if ($user)
		{
			if (session::renew($sid, $ip) == true)
			{
				$this->user_info = $this->get_info('id', $user['id'], array('id', 'user', 'rank'));
				$this->is_logged_in = true;
				return(true);
			}
			return(false);
		}
		return(false);
	}
	
	function login($user, $pass, $ip)
	{
		$exist = $this->get_info('user', $user, array('id', 'pass', 'salt'));
		if ($exist)
		{
			$pass = $this->gen_pass($pass, $exist['salt']);
			if ($pass == $exist['pass'])
			{
				$sid = $this->gen_salt($exist['salt']);
				$log_in = session::create($exist['id'], $sid, $ip);
				if ($log_in)
				{
					$_SESSION['sid'] = $sid;
					$this->user_info = $this->get_info('id', $exist['id'], array('id', 'user', 'rank'));
					$this->is_logged_in = true;
					return(true);
				}
				return('session');
			}
			return('password');
		}
		return('exist');
	}
	
	function get_info($from, $data, $returns = array('id', 'user', 'rank'))
	{
		global $db;
		
		$from = $db->escape($from);
		$data = $db->escape($data);
		foreach ($returns as $key => $val)
		{
			$returns[$key] = $db->escape($val);
		}
		$query = 'SELECT `' . implode('`, `', $returns) . "` FROM users WHERE `$from` = '$data';";
		$result = $db->query($query);
		if ($result)
		{
			$return = $db->frow($result);
			$db->free($result);
			return($return);
		}
		$db->free($result);
		return(false);
	}
	
	function gen_pass($pass, $salt)
	{
		$pass = md5($pass);
		$pass = md5($pass . $salt);
		return($pass);
	}
	
	function gen_salt($salt = null)
	{
		$return = mt_rand();
		$return = base_convert($return, 10, 36);
		$return = md5($return);
		$return = $return . md5(uniqid(null, true));
		$return = md5($return . $salt);
		return($return);
	}
	
}